package com.sphd.Restaurant.presenter;

import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.sphd.Restaurant.base.MyApplication;
import com.sphd.Restaurant.infos.AddressInfo;
import com.sphd.Restaurant.infos.CouponInfo;
import com.sphd.Restaurant.interfFace.VolleyCallBack;
import com.sphd.Restaurant.utils.JsonUtil;
import com.sphd.Restaurant.utils.VolleyErrorHelper;
import com.sphd.Restaurant.views.AffirmOrderView;


import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;
import java.util.Map;

/**
 * Created by Hu on 2016/10/11.
 */

public class AffirmOrderP extends BasePresenter implements VolleyCallBack<JSONObject> {
    AffirmOrderView affirmOrderView;

    public AffirmOrderP(AffirmOrderView affirmOrderView) {
        this.affirmOrderView = affirmOrderView;
    }

    @Override
    public void addData(String url) {
        affirmOrderView.showdialog();
        sendJsonObjectUrl(url, this);
    }

    public void addData(String url, Map<String, String> map) {
        affirmOrderView.showdialog();
        StringRequest stringRequest = new StringRequest(Request.Method.POST, url, response -> {
            int res = 0;
            try {
                res = new JSONObject(response).getInt("res");
                affirmOrderView.sendRes(res);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            affirmOrderView.dissmissdialog();

        }, error -> {

        affirmOrderView.sendAffirmError(error);
        affirmOrderView.dissmissdialog();
        } ) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                return map;

            }
        };
        MyApplication.getRequestQueue().add(stringRequest);
    }

    @Override
    public void onResponse(JSONObject object) {
        try {
            String isVip = object.getString("checkLogin");
            double account = object.getDouble("account");
            String gmtTime = object.getString("currentTime");
            List<AddressInfo> addressInfoList = JsonUtil.getListFromString(object.getString("sendInfo"), AddressInfo.class);
            List<CouponInfo> couponInfos = JsonUtil.getListFromString(object.getString("cards"), CouponInfo.class);
            affirmOrderView.sendList(isVip, account, addressInfoList, couponInfos,gmtTime);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        affirmOrderView.dissmissdialog();
    }

    @Override
    public void onErrorResponse(VolleyError error) {
        affirmOrderView.sendAffirmError(error);
        affirmOrderView.dissmissdialog();
        Toast.makeText(context, VolleyErrorHelper.getMessage(error),Toast.LENGTH_SHORT).show();
    }
}
